package com.gaofei.alipay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.gaofei.alipay.api.OrderFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("pay")
public class PayController {


    @Autowired
    private OrderFeign orderFeign;

    /**
     * 统一下单支付接口
     * @param orderId
     * @param amount
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping("toPay")
    public String toPay(String orderId,String amount) throws AlipayApiException {
        String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCspZuyimkZ0hG441eITVVQyeCfwV9BgTpDocDC7IG85gHqDFiORIsKyDKPH7O0GFAHFH4bE99o8vSfTsMFPqVmQ2Y2YgkR80wCkWkJ8GNA0CNF+CscxcasmFtIfJR5Dcoheu3zK9Ej7HzqndDNKKTV896AG+PtutO7tQhyEA16jT1fMGxy6mss8jh0N6jwHr2OtA7f8rlSM//nJmRLEJmw/ezPAkYXXH4HUS0CvrJUnnKMniM81t6129yTZI3jr3RHPhc8B5YRGV/HSebfJz3jZ83qzqBnniRj7KHI1inaIzDb3b4WHlxHTj/pXpf2qi7KYu82eUQ4kOhFDO4sizeBAgMBAAECggEARLYokFdb2wXrPb1lYf79PIkMGCja43QuHyqqUCnWvLqB+odtW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ersyFdTXLp1G0+9xXQNyh6iTYaAmwUZr3XEP/EJIlXgRAg9P/hHok19nWLoUpikY8oRGY8JtOIwgQ5/TqLIA46Zsga";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAio0KicEvQ/8404EWznkT1MCvomH3iVIYnrHRVXtL3xFXfRBxRBe5GTzbDLhayz1g+a/nYShUDaSYRcpdeqr9koQTwg8946JB5wC/SFcMFQdxdu4lyR+ZiyGI9bRgevZKqYyyc4n6nb0xLghpgPIcaQOwFLHRkiFh0jQwcTX0uuF4YTvxiYTFQk1oQKU1elfemhF4bqAq/K1xPhAtNxMPxH9HokGMklyf9a3e8gPtBy1dOv7g0yB7V5HuUR+88MgCUYjaN9Hx1LtMeP0I8YAOMSxQ4xBKOG3GPzy6rkvr68gdt1y25qKaqJWDJMSpzgbjFy2tltJGUEGx+rsA0ZWjkwIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000126621192");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);

        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        request.setReturnUrl("http://127.0.0.1:8084/pay/notify");
        model.setOutTradeNo(orderId);
        model.setTotalAmount(amount);
        model.setSubject("Iphone6 16G");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        request.setBizModel(model);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return pageRedirectionData;
    }
    /**
     * 支付通知: 同步通知,和异步通知
     * 同步通知一般生产环境不用,异步通知(测试需要使用内网穿透)
     * 主流做法,主动查询订单
     *
     * 支付通知回调接口
     */
    @RequestMapping("notify")
    public String notifyPayResult(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAio0KicEvQ/8404EWznkT1MCvomH3iVIYnrHRVXtL3xFXfRBxRBe5GTzbDLhayz1g+a/nYShUDaSYRcpdeqr9koQTwg8946JB5wC/SFcMFQdxdu4lyR+ZiyGI9bRgevZKqYyyc4n6nb0xLghpgPIcaQOwFLHRkiFh0jQwcTX0uuF4YTvxiYTFQk1oQKU1elfemhF4bqAq/K1xPhAtNxMPxH9HokGMklyf9a3e8gPtBy1dOv7g0yB7V5HuUR+88MgCUYjaN9Hx1LtMeP0I8YAOMSxQ4xBKOG3GPzy6rkvr68gdt1y25qKaqJWDJMSpzgbjFy2tltJGUEGx+rsA0ZWjkwIDAQAB", "UTF-8", "RSA2"); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            System.out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
            //1.得到这些信息之后说明收到了支付宝的通知
            //2.修改订单状态:待支付--->已支付
//            String s = orderFeign.updateOrderStatus(Integer.parseInt(out_trade_no));  //注释模拟掉单
//            if(s.equals("success")){
//                //3.修改状态成功-->重定向到商品列表页面
//                response.sendRedirect("http://localhost:8080/goodsList");
//            }

        }else {
            System.out.println("验签失败");
        }
        //——请在这里编写您的程序（以上代码仅作参考）——
        return "success";
    }

    /**
     * 统一收单交易查询
     * @return
     * @throws AlipayApiException
     */

    @RequestMapping("queryOrderFromAlipay")
    public Object queryBill(String outTradeNo) throws AlipayApiException {
        String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCspZuyimkZ0hG441eITVVQyeCfwV9BgTpDocDC7IG85gHqDFiORIsKyDKPH7O0GFAHFH4bE99o8vSfTsMFPqVmQ2Y2YgkR80wCkWkJ8GNA0CNF+CscxcasmFtIfJR5Dcoheu3zK9Ej7HzqndDNKKTV896AG+PtutO7tQhyEA16jT1fMGxy6mss8jh0N6jwHr2OtA7f8rlSM//nJmRLEJmw/ezPAkYXXH4HUS0CvrJUnnKMniM81t6129yTZI3jr3RHPhc8B5YRGV/HSebfJz3jZ83qzqBnniRj7KHI1inaIzDb3b4WHlxHTj/pXpf2qi7KYu82eUQ4kOhFDO4sizeBAgMBAAECggEARLYokFdb2wXrPb1lYf79PIkMGCja43QuHyqqUCnWvLqB+odtWznWaLUiwimo2L1wZFD4m4g+O0OurhSns1eqdlfOv0gnOfitwLvkpSsCJZJw53EMn4frO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RGY8JtOIwgQ5/TqLIA46Zsga";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAio0KicEvQ/8404EWznkT1MCvomH3iVIYnrHRVXtL3xFXfRBxRBe5GTzbDLhayz1g+a/nYShUDaSYRcpdeqr9koQTwg8946JB5wC/SFcMFQdxdu4lyR+ZiyGI9bRgevZKqYyyc4n6nb0xLghpgPIcaQOwFLHRkiFh0jQwcTX0uuF4YTvxiYTFQk1oQKU1elfemhF4bqAq/K1xPhAtNxMPxH9HokGMklyf9a3e8gPtBy1dOv7g0yB7V5HuUR+88MgCUYjaN9Hx1LtMeP0I8YAOMSxQ4xBKOG3GPzy6rkvr68gdt1y25qKaqJWDJMSpzgbjFy2tltJGUEGx+rsA0ZWjkwIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000126621192");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(outTradeNo);
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return response.getBody();
    }
}
